package com.tailyou.hms.firstapp.act;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ViewSwitcher;

import androidx.appcompat.app.AppCompatActivity;

import com.tailyou.hms.firstapp.R;

public class ImgWdgActivity extends AppCompatActivity {

    //总共10张图片
    private int[] mPic = new int[]{R.mipmap.pc1, R.mipmap.pc2, R.mipmap.pc3, R.mipmap.pc4,
            R.mipmap.pc5, R.mipmap.pc6, R.mipmap.pc7, R.mipmap.pc8, R.mipmap.pc9, R.mipmap.pc10};
    private ImageSwitcher imageSwitcher;
    private LinearLayout llPic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_img_wdg);
        llPic = findViewById(R.id.llPic);
        imageSwitcher = findViewById(R.id.imageSwitcher);
        //将10张缩略图添加到线性布局
        for (int i = 0; i < mPic.length; i++) {
            llPic.addView(genImage(i));
        }
        //设置ImageView渲染工厂
        imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                ImageView imageView = new ImageView(ImgWdgActivity.this);
                return imageView;
            }
        });
        //设置切换动画
        imageSwitcher.setInAnimation(this, android.R.anim.fade_in);
        imageSwitcher.setOutAnimation(this, android.R.anim.fade_out);
        imageSwitcher.setImageResource(mPic[0]);
    }

    //生成一个ImageView
    private View genImage(int i) {
        //在Java代码中新建ImageView
        ImageView imageView = new ImageView(ImgWdgActivity.this);
        //设置id
        imageView.setId(i);
        //设置宽高
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(192, 256);
        imageView.setLayoutParams(params);
        //设置图片缩放类型
        imageView.setScaleType(ImageView.ScaleType.FIT_START);
        //设置资源图片
        imageView.setImageResource(mPic[i]);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageSwitcher.setImageResource(mPic[i]);
            }
        });
        return imageView;
    }

}